import { Injectable } from '@nestjs/common';
import axios from 'axios';
import { CronJob } from 'cron';

@Injectable()
export class CronService {
    private readonly jobs: CronJob[];

    constructor() {
        this.jobs = [
            new CronJob(
                '0 0 * * *',
                async () => {
                    try {
                        const response = await axios.get('http://localhost:8081/api/trader/autopay');
                        if (response) console.log('Cron job autopay complete');
                    } catch (error) {
                        console.log(error);
                    }
                },
                null,
                true,
                'Europe/Moscow'
            ),
            new CronJob(
                '0 12 * * *',
                async () => {
                    try {
                        const response = await axios.get('http://localhost:8081/api/user/updateNotification');
                        if (response) console.log('Cron job notification complete');
                    } catch (error) {
                        console.log(error);
                    }
                },
                null,
                true,
                'Europe/Moscow'
            ),
        ];
    }

    async startWork() {
        await Promise.all(this.jobs.map((job) => job.start()));
    }
}
